// pages/component/index.js
import Toast from '@vant/weapp/toast/toast';
const app = getApp();
const promiseRequest = app.myRequest();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    "isNewUser": false,
    "server": app.globalData.server,
    "myUserInfo": {},
    // 单选框复选框选中的颜色
    "checkedColor": "#1AAD19",
    date: '',
    show: false,
    vanColCellSpan: 7,
    calendar: {
      showTitle: false,
      showSubtitle: false,
      minDate: 0,
      maxDate: 0,
      defaultDate: new Date().getTime(),
      year: new Date().getFullYear(),
      mounth: 0,
      showConfirm: false,
      poppable: false,
      mounths: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
      lunarDate: [],
      //  存放日历的所有日期对象
      days: []
    },
    memo: {
      times: [],
      detail: '',
      // 重复方式(0一次性,1每年重复)
      repetition: '',
      // 日历类型(0农历1新历)
      calendarType: 1,
      // 备忘录日期
      memoDate: new Date(),
      name: '',
      userId: ''
    },
    restMemo: {
      times: [],
      detail: '',
      // 重复方式(0一次性,1每年重复)
      repetition: '',
      // 日历类型(0农历1新历)
      calendarType: 1,
      // 备忘录日期
      memoDate: new Date(),
      name: '',
      userId: ''
    },
    formatter(day) {
      return day;
    },
  },

  jumpCanlender: function () {
    const nowDate = new Date();
    let that = this;
    const nowYear = nowDate.getFullYear();
    const year = that.data.calendar.year;
    const mounth = that.data.calendar.mounth;
    if (nowYear + 10 <= year || 1900 > year) {
      Toast('年份应该在1900和' + (nowYear + 10) + '之间!')
      return
    }
    if (mounth < 1 || mounth > 12) {
      Toast('月份应该在1和12之间!');
      return
    }
    this.getLunarCalendarDay(year, mounth);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    const myUserInfo = app.globalData.myUserInfo;
    const nowDate = new Date();
    const nowMounth = nowDate.getMonth();
    const nowYear = nowDate.getFullYear();
    let that = this;
    if (!myUserInfo || myUserInfo == {} || !myUserInfo.id) {
      await app.registOrLoginPromise().then(res => {
        if (res.statusCode == 200) {
          if (!!res.data && res.data.code == 200) {
            app.globalData.myUserInfo = res.data.data;
            this.setData({
              myUserInfo: res.data.data
            });
            that.getLunarCalendarDay(nowYear, nowMounth + 1);
          } else {
            Toast('调用登录接口失败,请稍后重试!')
          }
        } else {
          Toast(res.errMsg)
        }

      })
    } else {
      this.setData({
        myUserInfo: myUserInfo
      })
      that.getLunarCalendarDay(nowYear, nowMounth + 1);
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  },

  onChangeCalendarYear: function (e) {
    // 表单双向数据绑定
    var that = this;
    that.setData({
      "calendar.year": e.detail
    });
  },
  onChangeCalendarMounth: function (e) {
    // 表单双向数据绑定
    var that = this;
    that.setData({
      "calendar.mounth": e.detail
    });
  },

  getLunarCalendarDay: function (year, month) {
    let days = 30;
    if (([1, 3, 5, 7, 8, 10, 12].indexOf(month)) > -1 || (['1', '3', '5', '7', '8', '10', '12'].indexOf(month)) > -1) {
      days = 31;
    }
    if (month == 2) {
      days = 28;
      if (year % 4 == 0 && year & 100 != 0 || year % 400 == 0) {
        days = 29;
      }
    }
    let self = this;
    wx.request({
      url: self.data.server + "calendar/getLunarCalendar",
      method: "post",
      data: {
        "year": year,
        "month": month,
        "days": days,
        "userId": !!self.data.myUserInfo.id ? self.data.myUserInfo.id : app.globalData.myUserInfo.id
      },
      dataType: "json",
      responseType: "	text",
      success(result) {
        const data = result.data.data;
        self.setData({
          "calendar.minDate": new Date(year, self.data.calendar.mounths[month - 1], 1).getTime(),
          "calendar.maxDate": new Date(year, self.data.calendar.mounths[month - 1], days).getTime(),
          "calendar.year": year,
          "calendar.mounth": month,
          "calendar.lunarDate": data,
          // "calendar.lunarDate": data,
          formatter: function (day) {
            day.bottomInfo = data[day.text];
            const lunar = data[day.text];
            day.bottomInfo = lunar.lunarDay;
            if (lunar.haveMemo) {
              day.className = 'dayClass';
              day.topInfo = "●"
            }
            return day;
          }
        })
      }
    })
  },
  selectDate: function (day) {
    const date = day.detail;
    const dateYear = date.getFullYear();
    const dateMonth = date.getMonth();
    const dateDay = date.getDate();
    const self = this;
    const lunarDate = self.data.calendar.lunarDate;
    const chooseDate = lunarDate[dateDay];
    chooseDate.date = dateYear + '-' + (dateMonth < 9 ? ('0' + (dateMonth + 1)) : (dateMonth + 1)) + '-' + (dateDay < 10 ? '0' + (dateDay) : dateDay);
    this.setData({
      "calendar.chooseDate": chooseDate
    })
  },
  onChangeCalendarType: function ({ detail }) {
    let self = this;
    this.setData({
      "memo.calendarType": self.data.memo.calendarType == 0 ? 1 : 0
    })
  },
  /**
   * 重复方式修改
   */
  onChangeRepetition: function (event) {
    this.setData({
      "memo.repetition": event.detail,
    })
  },
  onChangeMemoTime: function (event) {
    this.setData({
      "memo.times": event.detail,
    });
  },

  fieldChange: function (event) {
    this.setData({
      [event.currentTarget.dataset.name]: event.detail
    })
  },

  /**
   * 添加日程记录
   */
  addMemo: function () {
    let self = this;
    const memo = self.data.memo;
    const chooseDate = self.data.calendar.chooseDate;
    debugger
    if (!chooseDate || !chooseDate.date || !chooseDate.lunarCalender) {
      Toast('请选择日期!');
      return
    } else {
      memo.memoDate = memo.calendarType == 0 ? new Date(chooseDate.lunarCalender) : new Date(chooseDate.date)
    }
    if (!memo.name) {
      Toast('姓名不能为空!');
      return
    }
    if (!memo.detail) {
      Toast('内容不能为空!');
      return
    }
    if (!memo.times || memo.times == [] || memo.times.length <= 0) {
      Toast('请选择提醒时间!');
      return
    }
    if (!memo.userId) {
      memo.userId = !!self.data.myUserInfo.id ? self.data.myUserInfo.id : app.globalData.myUserInfo.id;
      if (!memo.userId) {
        Toast('获取用户id失败,请稍后重试!');
        return
      }
    }
    promiseRequest.postRequest('memo/saveOrUpdateMemo', memo).then(res => {
      if (res.statusCode == 200) {
        self.jumpCanlender();
        this.setData({
          memo: self.data.restMemo
        })
      } else {
        Toast(res.errMsg)
      }

    })
  },
})